#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/select.h>
#include <cstring>

#define NN 64

int main(int argc, char const *argv[])
{
    if (argc != 2)
    {
        printf("Usage: %s <ip> <port>\n",argv[0]);
        return -1;
    }

    int server_socket = socket(AF_INET,SOCK_STREAM,0);
    if (server_socket == -1)
    {
        perror("socket err\n");
        return -1;
    }
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[1]));
    addr.sin_addr.s_addr = INADDR_ANY;

    if (bind(server_socket,(struct sockaddr*)&addr,sizeof(addr))==-1)
    {
        perror("bind err\n");
        return -1;
    }

    if (listen(server_socket,5)==-1)
    {
        perror("listen err\n");
        return -1;
    }

    printf("wait client connect\n");
    struct sockaddr_in client_addr;
    socklen_t client_addr_len =sizeof(client_addr);
    int client_socket=-1;
    client_socket=accept(server_socket,(struct sockaddr*)&client_addr,&client_addr_len);
    printf("ip = %s\n",inet_ntoa(client_addr.sin_addr));
    if (client_socket==-1)
    {
        perror("accept err\n");
        close(server_socket);
        return -1;
    }

    char buf[NN] = {'\0'};
    while (1)
    {
        recv(client_socket,buf,NN,0);
        if (strcmp("quit",buf)==0)
        {
            break;
        }
        
        printf("recv data:%s\n",buf);
        send(client_socket,buf,NN,0);
    }
    
    close(server_socket);

    return 0;
}
